<template>
  <div class="personal-center">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <i class="iconfont icon-book"></i>
        <span>考研真题训练系统</span>
      </div>
      <div class="user-info">
        <span class="welcome">欢迎回来，{{ userStore.username }}</span>
        <el-avatar :size="40" :src="userInfo.avatar"></el-avatar>
      </div>
    </header>

    <!-- 主体内容 -->
    <div class="main-container">
      <!-- 侧边导航 -->
      <div class="sidebar">
        <div class="user-card">
          <el-avatar :size="80" :src="userInfo.avatar"></el-avatar>
          <div class="user-details">
            <h3>{{ userStore.username }}</h3>
            <p>VIP {{ userInfo.vipLevel }} 会员</p>
            <p>积分: {{ userInfo.points }}</p>
          </div>
        </div>

        <el-menu
          default-active="3"
          class="side-menu"
        >
          <el-menu-item index="1" >
            <router-link to="/personal-center/info" class="menu-link">
              <i class="iconfont icon-user"></i>
              <span>个人信息</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="2">
            <router-link to="/personal-center/edit" class="menu-link">
              <i class="iconfont icon-edit"></i>
              <span>修改资料</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="3" class="active">
            <router-link to="/personal-center/feedback" class="menu-link">
              <i class="iconfont icon-message"></i>
              <span>消息反馈</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="4" >
            <router-link to="/personal-center/notifications" class="menu-link">
              <i class="iconfont icon-notification"></i>
              <span>通知设置</span>
            </router-link>
          </el-menu-item>
          <el-menu-item index="5" >
            <router-link to="/personal-center/cancel-account" class="menu-link">
              <i class="iconfont icon-logout"></i>
              <span>注销账户</span>
            </router-link>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 主内容区 -->
      <div class="content">
        <!-- 消息反馈 -->
        <div class="feedback-section">
          <h2 class="section-title">消息反馈</h2>
          <div class="feedback-content">
            <div class="feedback-form">
              <el-form :model="feedbackForm" label-width="80px" :rules="rules" ref="feedbackFormRef">
                <el-form-item label="反馈类型" prop="feedbackType">
                  <el-select v-model="feedbackForm.feedbackType" placeholder="请选择反馈类型">
                    <el-option label="功能建议" value="1"></el-option>
                    <el-option label="问题反馈" value="2"></el-option>
                    <el-option label="投诉建议" value="3"></el-option>
                    <el-option label="其他" value="4"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="反馈标题" prop="title">
                  <el-input
                    v-model="feedbackForm.title"
                    placeholder="请输入反馈标题"
                    maxlength="100"
                    show-word-limit
                  ></el-input>
                </el-form-item>
                <el-form-item label="反馈内容" prop="content">
                  <el-input
                    type="textarea"
                    :rows="5"
                    v-model="feedbackForm.content"
                    placeholder="请详细描述您的反馈内容"
                    maxlength="500"
                    show-word-limit
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button 
                    type="primary" 
                    @click="submitFeedback" 
                    :loading="submitLoading"
                  >
                    {{ submitLoading ? '提交中...' : '提交反馈' }}
                  </el-button>
                  <el-button @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <div class="feedback-history">
              <h3>
                历史反馈
                <el-button 
                  type="text" 
                  size="small" 
                  @click="loadFeedbackHistory" 
                  :loading="historyLoading"
                  style="float: right;"
                >
                  刷新
                </el-button>
              </h3>
              <div class="history-list" v-loading="historyLoading">
                <div v-if="feedbackHistory.length === 0" class="empty-history">
                  <p>暂无反馈记录</p>
                </div>
                <div v-for="item in feedbackHistory" :key="item.feedbackId" class="history-item">
                  <div class="history-header">
                    <span class="type">{{ getTypeLabel(item.feedbackType) }}</span>
                    <span class="date">{{ formatDate(item.createdAt) }}</span>
                  </div>
                  <div class="history-title">{{ item.title }}</div>
                  <div class="history-content">{{ item.content }}</div>
                  <div class="history-status" :class="getStatusClass(item.status)">
                    {{ getStatusLabel(item.status) }}
                  </div>
                  <div v-if="item.adminReply && item.adminReply.trim()" class="admin-reply">
                    <div class="reply-label">管理员回复：</div>
                    <div class="reply-content">{{ item.adminReply }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '@/store/user'
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'MessageFeedback',
  setup() {
    const userStore = useUserStore()
    
    onMounted(() => {
      userStore.initialize()
    })
    
    return {
      userStore
    }
  },
  data() {
    return {
      userInfo: {
        username: '考研学子',
        email: 'kaoyan@example.com',
        phone: '13800138000',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        vipLevel: 3,
        points: 1280,
        vipExpiry: '2024-12-31',
        studyDays: 86,
        completed: 1240,
        correctRate: 78
      },
      feedbackForm: {
        feedbackType: '',
        title: '',
        content: ''
      },
      rules: {
        feedbackType: [
          { required: true, message: '请选择反馈类型', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入反馈标题', trigger: 'blur' },
          { min: 2, max: 100, message: '标题长度应在2-100个字符之间', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入反馈内容', trigger: 'blur' },
          { min: 10, max: 500, message: '内容长度应在10-500个字符之间', trigger: 'blur' }
        ]
      },
      feedbackHistory: [],
      submitLoading: false,
      historyLoading: false,
      baseURL: 'http://localhost:8080'
    };
  },
  mounted() {
    this.loadFeedbackHistory();
  },
  methods: {
    // 获取用户ID
    getUserId() {
      return this.userStore.userId || localStorage.getItem('userId') || '2';
    },

    // 加载用户的反馈历史
    async loadFeedbackHistory() {
      this.historyLoading = true;
      try {
        const userId = this.getUserId();
        console.log('正在加载用户反馈历史，用户ID:', userId);
        const response = await axios.get(`${this.baseURL}/feedback/user/${userId}`);
        console.log('反馈历史数据:', response.data);
        this.feedbackHistory = response.data;
      } catch (error) {
        console.error('加载反馈历史失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          ElMessage.error(`加载失败: ${error.response.status} ${error.response.statusText}`);
        } else {
          ElMessage.error('网络连接失败，请检查后端服务是否正常运行');
        }
      } finally {
        this.historyLoading = false;
      }
    },

    // 提交反馈
    async submitFeedback() {
      this.$refs.feedbackFormRef.validate(async (valid) => {
        if (!valid) {
          return false;
        }

        this.submitLoading = true;
        try {
          // 确保数据格式正确
          const feedbackData = {
            userId: parseInt(this.getUserId()), // 确保是数字
            username: this.userStore.username || '测试用户',
            feedbackType: this.feedbackForm.feedbackType, // 现在是数字字符串 "1", "2", "3", "4"
            title: this.feedbackForm.title.trim(), // 去除首尾空格
            content: this.feedbackForm.content.trim() // 去除首尾空格
          };

          console.log('准备提交的反馈数据:', feedbackData);
          
          const response = await axios.post(`${this.baseURL}/feedback/insert`, feedbackData, {
            headers: {
              'Content-Type': 'application/json'
            }
          });
          
          console.log('提交响应:', response.data);
          
          ElMessage.success('反馈提交成功，感谢您的建议！');
          this.resetForm();
          // 重新加载反馈历史
          await this.loadFeedbackHistory();
        } catch (error) {
          console.error('提交反馈失败:', error);
          if (error.response) {
            console.error('错误详情:', error.response.data);
            console.error('错误状态:', error.response.status);
            
            let errorMessage = '提交失败';
            if (error.response.data && error.response.data.message) {
              errorMessage = error.response.data.message;
            } else if (error.response.status === 500) {
              errorMessage = '服务器内部错误，请稍后重试';
            }
            
            ElMessage.error(`${errorMessage} (${error.response.status})`);
          } else {
            ElMessage.error('网络连接失败，请检查后端服务是否正常运行');
          }
        } finally {
          this.submitLoading = false;
        }
      });
    },

    // 重置表单
    resetForm() {
      this.$refs.feedbackFormRef.resetFields();
      this.feedbackForm = {
        feedbackType: '',
        title: '',
        content: ''
      };
    },

    // 获取反馈类型标签
    getTypeLabel(type) {
      const types = {
        // 数字格式（主要格式 - 新提交的数据）
        '1': '功能建议',
        '2': '问题反馈',
        '3': '投诉建议',
        '4': '其他',
        // 数字类型（兼容性）
        1: '功能建议',
        2: '问题反馈',
        3: '投诉建议',
        4: '其他',
        // 历史数据格式（从控制台看到的实际值）
        'suggestion': '功能建议',
        'question': '问题反馈',
        'other': '其他',
        'system': '系统问题',
        // 单字母格式（兼容性）
        'S': '功能建议',
        'B': '问题反馈', 
        'C': '投诉建议',
        'O': '其他',
        // 英文格式扩展（兼容性）
        'bug': '问题反馈',
        'complaint': '投诉建议',
        'SUGGESTION': '功能建议',
        'QUESTION': '问题反馈',
        'BUG': '问题反馈',
        'COMPLAINT': '投诉建议',
        'OTHER': '其他',
        'SYSTEM': '系统问题',
        // 中文格式（如果数据库直接存储中文）
        '功能建议': '功能建议',
        '问题反馈': '问题反馈',
        '投诉建议': '投诉建议',
        '其他': '其他',
        '系统问题': '系统问题',
        // 其他可能格式
        'suggest': '功能建议',
        'feedback': '问题反馈',
        'complain': '投诉建议',
        'issue': '问题反馈'
      };
      console.log('反馈类型原始值:', type, '类型:', typeof type, '映射结果:', types[type]);
      return types[type] || `未知类型(${type})`;
    },

    // 获取状态标签
    getStatusLabel(status) {
      const statusLabels = {
        // 数字格式
        '0': '处理中',
        '1': '已处理',
        '2': '已关闭',
        // 数字类型
        0: '处理中',
        1: '已处理',
        2: '已关闭',
        // 大写格式（兼容性）
        'PENDING': '处理中',
        'PROCESSING': '处理中',
        'RESOLVED': '已处理',
        'CLOSED': '已关闭',
        // 小写格式（兼容性）
        'pending': '处理中',
        'processing': '处理中',
        'resolved': '已处理',
        'closed': '已关闭'
      };
      console.log('状态原始值:', status, '类型:', typeof status, '映射结果:', statusLabels[status]);
      return statusLabels[status] || `未知状态(${status})`;
    },

    // 获取状态样式类
    getStatusClass(status) {
      const statusClasses = {
        // 数字格式
        '0': 'pending',
        '1': 'resolved',
        '2': 'resolved',
        // 数字类型
        0: 'pending',
        1: 'resolved',
        2: 'resolved',
        // 字符串格式（兼容性）
        'PENDING': 'pending',
        'PROCESSING': 'pending',
        'RESOLVED': 'resolved',
        'CLOSED': 'resolved',
        'pending': 'pending',
        'processing': 'pending',
        'resolved': 'resolved',
        'closed': 'resolved'
      };
      return statusClasses[status] || 'pending';
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      try {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      } catch (error) {
        console.error('日期格式化失败:', error);
        return dateString;
      }
    }
  }
};
</script>

<style scoped>
.personal-center {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  height: 60px;
  background: linear-gradient(135deg, #1e5799 0%,#207cca 100%);
  color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.logo {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
}

.logo .iconfont {
  font-size: 28px;
  margin-right: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.welcome {
  margin-right: 15px;
  font-size: 14px;
}

.main-container {
  display: flex;
  max-width: 1400px;
  margin: 20px auto;
  padding: 0 20px;
}

.sidebar {
  width: 260px;
  margin-right: 20px;
}

.user-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.user-details h3 {
  margin: 15px 0 5px;
  font-size: 18px;
}

.user-details p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.side-menu {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.side-menu .iconfont {
  margin-right: 10px;
  font-size: 18px;
}

.side-menu .el-menu-item {
  cursor: pointer;
}

.side-menu .el-menu-item.active {
  background-color: #ecf5ff;
  color: #409EFF;
}

.content {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-title {
  color: #303133;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.feedback-content {
  display: flex;
  gap: 30px;
}

.feedback-form {
  flex: 1;
}

.feedback-history {
  flex: 1;
  background: #fafbfc;
  border-radius: 8px;
  padding: 20px;
}

.feedback-history h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #303133;
}

.empty-history {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.history-item {
  padding: 15px;
  background: white;
  border-radius: 6px;
  margin-bottom: 15px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
  border-left: 4px solid #409EFF;
  position: relative;
}

.history-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.history-header .type {
  background: #ecf5ff;
  color: #409EFF;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.history-header .date {
  color: #909399;
  font-size: 12px;
}

.history-title {
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
  font-size: 14px;
}

.history-content {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 10px;
}

.history-status {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.history-status.pending {
  background: #fdf6ec;
  color: #e6a23c;
}

.history-status.resolved {
  background: #f0f9eb;
  color: #67c23a;
}

.admin-reply {
  margin-top: 10px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #67c23a;
}

.reply-label {
  font-size: 12px;
  color: #67c23a;
  margin-bottom: 5px;
  font-weight: bold;
}

.reply-content {
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .feedback-content {
    flex-direction: column;
  }
  
  .main-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    margin-right: 0;
    margin-bottom: 20px;
  }
}
</style>